package cn.itsource.org.service.impl;

import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.org.domain.Department;
import cn.itsource.org.mapper.DepartmentMapper;
import cn.itsource.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 业务实现类：部门
 * @author: Bug修复机
 * @date: 2022/8/12 : 19:21
 * @version: ver1.0
 * @email tangli@itsource.cn
 */
@Service //1.将当前类交给Spring管理 2.实例化对象的注解 //前提：扫描包路径
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    //注入：从Spring容器中获取当前类或子类的对象  赋值 给当前属性
    @Autowired
    //IDEA以为Spring容器中没有该类型或其子类型的对象，又在使用，所以报错
    //它错了 - 因为已经通过在App中@MapperScan("cn.itsource.*.mapper")已经生成了
    private DepartmentMapper departmentMapper;


    @Override
    public List<Department> deptTree() {
        //将所有的部门添加的Map中 - 为了根据id去获取
        List<Department> departments = departmentMapper.loadAll();
        Map<Long,Department> map =  new HashMap<>();
        //将每一个部门的id和对象保存在Map
        for (Department department : departments) {
            map.put(department.getId(),department);
        }

        //查询部门树
        List<Department> deptTree = new ArrayList<>();
        for (Department department : departments) {
            //如果没有父id - 顶级部门
            if(department.getParent_id()==null){//顶级部门
                deptTree.add(department);
            }else{
                //获取父部门id
                Long parent_id = department.getParent_id();
                //获取父部门
                Department parentDept = map.get(parent_id);
                if(parentDept!=null){
                    //将自己添加到父部门的Children中
                    parentDept.getChildren().add(department);
                }
            }
        }
        return deptTree;
    }
}
